package sc.prototype.pfs.eventnotify.executor.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.Assert;

import sc.prototype.pfs.eventnotify.executor.NotifyExecutor;
import sc.prototype.pfs.eventnotify.executor.NotifyExecutorFactory;
import sc.prototype.pfs.eventnotify.executor.NotifyTaskManager;
import sc.prototype.pfs.eventnotify.model.Notice;
import sc.prototype.pfs.eventnotify.model.NotifyContext;
import sc.prototype.pfs.eventnotify.model.NotifyResult;

public class DefaultNotifyTaskManager implements NotifyTaskManager {

    NotifyExecutorFactory notifyExecutorFactory;

    ThreadPoolTaskExecutor notifyTaskExecutor;

    public void validate(NotifyExecutor notifyExecutor, Notice notice, NotifyContext context) {
        Assert.notNull(notifyExecutor, "通知执行器不能为空！");
        Assert.notNull(notice, "通知对象不能为空！");
        Assert.notNull(context, "通知上下文不能为空！");
    }

    @Override
    public void processNotifyTask(Notice notice, NotifyContext context) {
        NotifyExecutor notifyExecutor = notifyExecutorFactory.create(notice);
        validate(notifyExecutor, notice, context);
        NotifyTaskRunner taskRunner = new NotifyTaskRunner(notifyExecutor, notice, context);
        notifyTaskExecutor.execute(taskRunner);
    }

    public static class NotifyTaskRunner implements Runnable {

        public NotifyTaskRunner(NotifyExecutor notifyExecutor, Notice notice, NotifyContext context) {
            this.notifyExecutor = notifyExecutor;
            this.notice = notice;
            this.context = context;
        }

        Logger logger = LoggerFactory.getLogger(this.getClass());

        NotifyExecutor notifyExecutor;
        Notice notice;
        NotifyContext context;

        @Override
        public void run() {
            try {
                NotifyResult notifyRst = notifyExecutor.sendNotice(notice, context);
                logger.info("{}：通知结果：{}", context.getLogPrefix(), notifyRst);
                //更新状态

            } catch (Exception e) {
                logger.error(context.getLogPrefix() + "：执行通知异常：", e);
            }
        }

    }

    public void setNotifyExecutorFactory(NotifyExecutorFactory notifyExecutorFactory) {
        this.notifyExecutorFactory = notifyExecutorFactory;
    }

    public void setNotifyTaskExecutor(ThreadPoolTaskExecutor notifyTaskExecutor) {
        this.notifyTaskExecutor = notifyTaskExecutor;
    }

}
